﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.Web;
using DGM.Util.Helpers.OAuth_dotnet.Sources;

namespace DGM.Util.Helpers.OAuth_dotnet
{
  public abstract class OAuthBase: IOAuth
  {
    protected IOAuthGetAccessTokenCallback Callback { get; set; }



    /// <summary>
    /// Provides a predefined set of algorithms that are supported officially by the protocol
    /// </summary>
    public enum SignatureTypes
    {
      HMACSHA1,
      PLAINTEXT,
      RSASHA1
    }

    /// <summary>
    /// Provides an internal structure to sort the query parameter
    /// </summary>
    protected class QueryParameter
    {
      public string Name { get; private set; }
      public string Value { get; private set; }

      public QueryParameter(string name, string value)
      {
        Name = name;
        Value = value;
      }
    }

    /// <summary>
    /// Comparer class used to perform the sorting of the query parameters
    /// </summary>
    protected class QueryParameterComparer : IComparer<QueryParameter>
    {

      public int Compare(QueryParameter x, QueryParameter y)
      {
        if (x.Name == y.Name)
        {
          return string.Compare(x.Value, y.Value);
        }
        return string.Compare(x.Name, y.Name);
      }
    }

    public enum Method { GET, POST, PUT, DELETE };

    protected const string OAuthVersion = "1.0";
    protected const string OAuthParameterPrefix = "oauth_";

    //
    // List of know and used oauth parameters' names
    //        
    protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
    protected const string OAuthCallbackKey = "oauth_callback";
    protected const string OAuthVersionKey = "oauth_version";
    protected const string OAuthSignatureMethodKey = "oauth_signature_method";
    protected const string OAuthSignatureKey = "oauth_signature";
    protected const string OAuthTimestampKey = "oauth_timestamp";
    protected const string OAuthNonceKey = "oauth_nonce";
    protected const string OAuthTokenKey = "oauth_token";
    protected const string OAauthVerifier = "oauth_verifier";
    protected const string OAuthTokenSecretKey = "oauth_token_secret";

    protected const string HMACSHA1SignatureType = "HMAC-SHA1";
    protected const string PlainTextSignatureType = "PLAINTEXT";
    protected const string RSASHA1SignatureType = "RSA-SHA1";

    public string Verifier { get; set; }
    public string Token { get; set; }
    public string TokenSecret { get; set; }

    public abstract string UserAgent { get; }
    public abstract string RequestTokenUrl { get; }
    public abstract string AuthorizeUrl { get; }
    public abstract string AccessTokenUrl { get; }
    public abstract string CallbackUrl { get; }
    public abstract string RealmUrl { get; }

    //this values you should get from the API you want to connect to
    public abstract string ConsumerKey { get; }
    public abstract string ConsumerSecret { get; }

    protected string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";


    protected OAuthBase(IOAuthGetAccessTokenCallback callback)
    {
      Callback = callback;
    }

    #region public methods

    public string GetRequestToken()
    {
      string ret = null;
      string response = OAuthWebRequest(Method.POST, RequestTokenUrl, string.Empty);
      if (response.Length > 0)
      {
        var qs = HttpUtility.ParseQueryString(response);
        if (qs["oauth_token"] != null)
        {
          Token = qs["oauth_token"];
          TokenSecret = qs["oauth_token_secret"];
          ret = Token;
        }
      }
      return ret;
    }

    public string GetAccessToken()
    {
      if (string.IsNullOrEmpty(Token) || string.IsNullOrEmpty(Verifier))
      {
        throw new Exception("The request token and verifier were not set");;
      }

      string response = OAuthWebRequest(Method.POST, AccessTokenUrl, string.Empty);

      if (response.Length > 0)
      {
        var qs = HttpUtility.ParseQueryString(response);
        if (qs["oauth_token"] != null)
        {
          this.Token = qs["oauth_token"];
        }
        if (qs["oauth_token_secret"] != null)
        {
          this.TokenSecret = qs["oauth_token_secret"];
        }
      }

      return Token;
    }

    public string AuthorizeToken()
    {
      if (string.IsNullOrEmpty(Token))
      {
        throw new Exception("The request token is not set");;
      }

      var tokenVirifier = Callback.Authorize(this);
      Token = tokenVirifier.Token;
      Verifier = tokenVirifier.Verifier;

      return Token;
    }

    public string AuthorizationLink
    {
      get { return AuthorizeUrl + "?oauth_token=" + Token; }
    }

    public string OAuthWebRequest(Method method, string url, string postData)
    {
      string outUrl = "";
      string querystring = "";
      string ret = "";

      //Setup postData for signing.
      //Add the postData to the querystring.
      if (method == Method.POST)
      {
        if (postData.Length > 0)
        {
          //Decode the parameters and re-encode using the oAuth UrlEncode method.
          NameValueCollection qs = HttpUtility.ParseQueryString(postData);
          postData = "";
          foreach (string key in qs.AllKeys)
          {
            if (postData.Length > 0)
            {
              postData += "&";
            }
            qs[key] = HttpUtility.UrlDecode(qs[key]);
            qs[key] = UrlEncode(qs[key]);
            postData += key + "=" + qs[key];

          }
          if (url.IndexOf("?") > 0)
          {
            url += "&";
          }
          else
          {
            url += "?";
          }
          url += postData;
        }
      }

      Uri uri = new Uri(url);

      string nonce = this.GenerateNonce();
      string timeStamp = this.GenerateTimeStamp();

      string callback = "";
      if (url.ToString().Contains(RequestTokenUrl))
        callback = CallbackUrl;

      //Generate Signature
      string sig = GenerateSignature(uri,
          ConsumerKey,
          ConsumerSecret,
          Token,
          TokenSecret,
          method.ToString(),
          timeStamp,
          nonce,
          callback,
          out outUrl,
          out querystring);


      querystring += "&oauth_signature=" + HttpUtility.UrlEncode(sig);

      //Convert the querystring to postData
      if (method == Method.POST)
      {
        postData = querystring;
        querystring = "";
      }

      if (querystring.Length > 0)
      {
        outUrl += "?";
      }

      if (method == Method.POST || method == Method.GET)
        ret = WebRequest(method, outUrl + querystring, postData);

      return ret;
    }

    public string WebRequest(Method method, string url, string postData)
    {
      HttpWebRequest webRequest = null;
      StreamWriter requestWriter = null;
      string responseData = "";

      webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
      webRequest.Method = method.ToString();
      webRequest.ServicePoint.Expect100Continue = false;
      webRequest.UserAgent = UserAgent;
      webRequest.Timeout = 20000;

      if (method == Method.POST)
      {
        webRequest.ContentType = "application/x-www-form-urlencoded";

        requestWriter = new StreamWriter(webRequest.GetRequestStream());
        try
        {
          requestWriter.Write(postData);
        }
        catch
        {
          throw;
        }
        finally
        {
          requestWriter.Close();
          requestWriter = null;
        }
      }

      responseData = WebResponseGet(webRequest);

      webRequest = null;

      return responseData;

    }

    /// <summary>
    /// WebRequestWithPut
    /// </summary>
    /// <param name="method">WebRequestWithPut</param>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <returns></returns>
    public string ApiWebRequest(string method, string url, string postData)
    {
      Uri uri = new Uri(url);
      string nonce = this.GenerateNonce();
      string timeStamp = this.GenerateTimeStamp();

      string outUrl, querystring;

      //Generate Signature
      string sig = GenerateSignature(uri,
          ConsumerKey,
          ConsumerSecret,
          Token,
          TokenSecret,
          method,
          timeStamp,
          nonce,
          null,
          out outUrl,
          out querystring);

      HttpWebRequest webRequest = null;

      webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
      webRequest.Method = method;
      webRequest.Credentials = CredentialCache.DefaultCredentials;
      webRequest.AllowWriteStreamBuffering = true;

      webRequest.PreAuthenticate = true;
      webRequest.ServicePoint.Expect100Continue = false;
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

      webRequest.Headers.Add("Authorization", "OAuth realm=\"" + RealmUrl + "\",oauth_consumer_key=\"" + ConsumerKey + "\",oauth_token=\"" + Token + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_signature=\"" + HttpUtility.UrlEncode(sig) + "\",oauth_timestamp=\"" + timeStamp + "\",oauth_nonce=\"" + nonce + "\",oauth_verifier=\"" + this.Verifier + "\", oauth_version=\"1.0\"");

      if (postData != null)
      {
        byte[] fileToSend = Encoding.UTF8.GetBytes(postData);
        webRequest.ContentLength = fileToSend.Length;

        Stream reqStream = webRequest.GetRequestStream();

        reqStream.Write(fileToSend, 0, fileToSend.Length);
        reqStream.Close();
      }

      string returned = WebResponseGet(webRequest);

      return returned;
    }

    /// <summary>
    /// Process the web response.
    /// </summary>
    /// <param name="webRequest">The request object.</param>
    /// <returns>The response data.</returns>
    public string WebResponseGet(HttpWebRequest webRequest)
    {
      StreamReader responseReader = null;
      string responseData = "";

      try
      {
        responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
        responseData = responseReader.ReadToEnd();
      }
      catch (Exception e)
      {
        throw e;
      }
      finally
      {
        webRequest.GetResponse().GetResponseStream().Close();
        responseReader.Close();
        responseReader = null;
      }

      return responseData;
    }

    #endregion

    /// <summary>
    /// Helper function to compute a hash value
    /// </summary>
    /// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
    /// <param name="data">The data to hash</param>
    /// <returns>a Base64 string of the hash value</returns>
    private static string ComputeHash(HashAlgorithm hashAlgorithm, string data)
    {
      if (hashAlgorithm == null)
      {
        throw new ArgumentNullException("hashAlgorithm");
      }

      if (string.IsNullOrEmpty(data))
      {
        throw new ArgumentNullException("data");
      }

      byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
      byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);

      return Convert.ToBase64String(hashBytes);
    }

    /// <summary>
    /// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
    /// </summary>
    /// <param name="parameters">The query string part of the Url</param>
    /// <returns>A list of QueryParameter each containing the parameter name and value</returns>
    private List<QueryParameter> GetQueryParameters(string parameters)
    {
      if (parameters.StartsWith("?"))
      {
        parameters = parameters.Remove(0, 1);
      }

      List<QueryParameter> result = new List<QueryParameter>();

      if (!string.IsNullOrEmpty(parameters))
      {
        string[] p = parameters.Split('&');
        foreach (string s in p)
        {
          if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix))
          {
            if (s.IndexOf('=') > -1)
            {
              string[] temp = s.Split('=');
              result.Add(new QueryParameter(temp[0], temp[1]));
            }
            else
            {
              result.Add(new QueryParameter(s, string.Empty));
            }
          }
        }
      }

      return result;
    }

    /// <summary>
    /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
    /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
    /// </summary>
    /// <param name="value">The value to Url encode</param>
    /// <returns>Returns a Url encoded string</returns>
    public string UrlEncode(string value)
    {
      StringBuilder result = new StringBuilder();

      foreach (char symbol in value)
      {
        if (UnreservedChars.IndexOf(symbol) != -1)
        {
          result.Append(symbol);
        }
        else
        {
          result.Append('%' + string.Format("{0:X2}", (int)symbol));
        }
      }

      return result.ToString();
    }

    /// <summary>
    /// Normalizes the request parameters according to the spec
    /// </summary>
    /// <param name="parameters">The list of parameters already sorted</param>
    /// <returns>a string representing the normalized parameters</returns>
    protected string NormalizeRequestParameters(IList<QueryParameter> parameters)
    {
      StringBuilder sb = new StringBuilder();
      QueryParameter p = null;
      for (int i = 0; i < parameters.Count; i++)
      {
        p = parameters[i];
        sb.AppendFormat("{0}={1}", p.Name, p.Value);

        if (i < parameters.Count - 1)
        {
          sb.Append("&");
        }
      }

      return sb.ToString();
    }

    /// <summary>
    /// Generate the signature base that is used to produce the signature
    /// </summary>
    /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
    /// <param name="consumerKey">The consumer key</param>        
    /// <param name="token">The token, if available. If not available pass null or an empty string</param>
    /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
    /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
    /// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
    /// <returns>The signature base</returns>
    public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string callback, string signatureType, out string normalizedUrl, out string normalizedRequestParameters)
    {
      if (token == null)
      {
        token = string.Empty;
      }

      if (tokenSecret == null)
      {
        tokenSecret = string.Empty;
      }

      if (string.IsNullOrEmpty(consumerKey))
      {
        throw new ArgumentNullException("consumerKey");
      }

      if (string.IsNullOrEmpty(httpMethod))
      {
        throw new ArgumentNullException("httpMethod");
      }

      if (string.IsNullOrEmpty(signatureType))
      {
        throw new ArgumentNullException("signatureType");
      }

      normalizedUrl = null;
      normalizedRequestParameters = null;

      List<QueryParameter> parameters = GetQueryParameters(url.Query);
      parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
      parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
      parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
      parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
      parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));

      //TODO: Make this less of a hack
      if (!string.IsNullOrEmpty(callback))
      {
        parameters.Add(new QueryParameter(OAuthCallbackKey, UrlEncode(callback)));
      }

      if (!string.IsNullOrEmpty(token))
      {
        parameters.Add(new QueryParameter(OAuthTokenKey, token));
      }

      if (!string.IsNullOrEmpty(Verifier))
      {
        parameters.Add(new QueryParameter(OAauthVerifier, Verifier));
      }


      parameters.Sort(new QueryParameterComparer());


      normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
      if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
      {
        normalizedUrl += ":" + url.Port;
      }
      normalizedUrl += url.AbsolutePath;
      normalizedRequestParameters = NormalizeRequestParameters(parameters);

      StringBuilder signatureBase = new StringBuilder();
      signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
      signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
      signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));

      return signatureBase.ToString();
    }

    /// <summary>
    /// Generate the signature value based on the given signature base and hash algorithm
    /// </summary>
    /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
    /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
    /// <returns>A base64 string of the hash value</returns>
    public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
    {
      return ComputeHash(hash, signatureBase);
    }

    /// <summary>
    /// Generates a signature using the HMAC-SHA1 algorithm
    /// </summary>		
    /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
    /// <param name="consumerKey">The consumer key</param>
    /// <param name="consumerSecret">The consumer seceret</param>
    /// <param name="token">The token, if available. If not available pass null or an empty string</param>
    /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
    /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
    /// <returns>A base64 string of the hash value</returns>
    public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string callback, out string normalizedUrl, out string normalizedRequestParameters)
    {
      return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, callback, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
    }

    /// <summary>
    /// Generates a signature using the specified signatureType 
    /// </summary>		
    /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
    /// <param name="consumerKey">The consumer key</param>
    /// <param name="consumerSecret">The consumer seceret</param>
    /// <param name="token">The token, if available. If not available pass null or an empty string</param>
    /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
    /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
    /// <param name="signatureType">The type of signature to use</param>
    /// <returns>A base64 string of the hash value</returns>
    public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string callback, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters)
    {
      normalizedUrl = null;
      normalizedRequestParameters = null;

      switch (signatureType)
      {
        case SignatureTypes.PLAINTEXT:
          return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
        case SignatureTypes.HMACSHA1:
          string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, callback, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters);
          HMACSHA1 hmacsha1 = new HMACSHA1();
          hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));

          return GenerateSignatureUsingHash(signatureBase, hmacsha1);
        case SignatureTypes.RSASHA1:
          throw new NotImplementedException();
        default:
          throw new ArgumentException("Unknown signature type", "signatureType");
      }
    }

    /// <summary>
    /// Generate the timestamp for the signature        
    /// </summary>
    /// <returns></returns>

    public virtual string GenerateTimeStamp()
    {
      // Default implementation of UNIX time of the current UTC time
      TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
      return Convert.ToInt64(ts.TotalSeconds).ToString();
    }

    /*
   public virtual string GenerateTimeStamp() {
       // Default implementation of UNIX time of the current UTC time
       TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
       string timeStamp = ts.TotalSeconds.ToString();
       timeStamp = timeStamp.Substring(0, timeStamp.IndexOf(","));
       return Convert.ToInt64(timeStamp).ToString(); 
   }*/

    /// <summary>
    /// Generate a nonce
    /// </summary>
    /// <returns></returns>
    public virtual string GenerateNonce()
    {
      var random = new Random();

      // Just a simple implementation of a random number between 123400 and 9999999
      return random.Next(123400, 9999999).ToString();
    }

  }
}

